package com.tnxst.phexamination.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.tnxst.phexamination.R;
import com.tnxst.phexamination.activity.IndexActivity;
import com.tnxst.phexamination.activity.PhysicalDetermineActivity;
import com.tnxst.phexamination.adapter.RecordTcmHealthElderlyAdapter;
import com.tnxst.phexamination.constant.HISConfig;
import com.tnxst.phexamination.databinding.RecordTcmHealthElderlyBinding;
import com.tnxst.phexamination.dto.InhabitantDTO;
import com.tnxst.phexamination.dto.TCMHealthDTO;
import com.tnxst.phexamination.public_health_docking_interface.TuberculosisInterface;
import com.tnxst.phexamination.utils.GsonUtils;
import com.tnxst.phexamination.utils.ReflectUtils;
import com.tnxst.phexamination.utils.StringUtils;
import com.tnxst.phexamination.utils.Utils;
import com.tnxst.phexamination.utils.WebServiceUtils;
import com.tnxst.phexamination.viewmodel.GlobalViewModel;

import org.apache.commons.collections.CollectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class RecordTcmHealthElderlyFragment extends Fragment{

    private GlobalViewModel viewModel;

    private RecordTcmHealthElderlyBinding binding;

    private Context context;

    private RecordTcmHealthElderlyAdapter adapter;

    private TCMHealthDTO tcmHealthDTO;

    private InhabitantDTO inhabitantDTO;

    private Map<String,Integer> scores;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        binding = DataBindingUtil.inflate(inflater, R.layout.record_tcm_health_elderly, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = ViewModelProviders.of(requireActivity()).get(GlobalViewModel.class);
        context = getActivity();
        initData();
        initView();
    }

    private void initData() {
        Bundle arguments = getArguments();
        scores = new LinkedHashMap<>();

        if (arguments == null){
            tcmHealthDTO = new TCMHealthDTO();
        }
        else {
            tcmHealthDTO = (TCMHealthDTO) arguments.get("tcmHealthDTO");
            inhabitantDTO = viewModel.getInhabitantRepository().findByField("ID",tcmHealthDTO.getResident());
            if (inhabitantDTO == null){
                hideAddFragment();
                return;
            }
        }


    }


    private void initView(){
        List<String> str = Arrays.asList(getResources().getStringArray(R.array.tcm));
        binding.recycler.setLayoutManager(new LinearLayoutManager(context));
        adapter = new RecordTcmHealthElderlyAdapter(str,tcmHealthDTO);
        binding.recycler.setAdapter(adapter);

        //下一步
        binding.button54.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isAllChecked())
                    return;
                if (inhabitantDTO == null){
                    Utils.Toast(context,"请先选择病人！");
                    return;
                }
                save();
                Intent intent = new Intent(context, PhysicalDetermineActivity.class);
                intent.putExtra("tcmHealthDTO",tcmHealthDTO);
                intent.putExtra("scores",GsonUtils.toJson(scores));
                startActivity(intent);
            }
        });

        binding.button53.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideAddFragment();
            }
        });

        //病人信息
        binding.editText2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String idCard = s.toString();
                if (idCard.length() >= 2 ){
                    List<InhabitantDTO> dtoList = viewModel.getInhabitantRepository().findByFieldList("NAME", idCard);
                    if (!CollectionUtils.isEmpty(dtoList)){
                        InhabitantDTO i = dtoList.get(0);
                        if (i != null){
                            inhabitantDTO = i;
//                            if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//                                TuberculosisInterface.verifyIsTbPatient(inhabitantDTO.getID(), new WebServiceUtils.Response<Map>() {
//                                    @Override
//                                    public void onSuccess(Map result) {
//                                        String is = result.get("Msg").toString();
//                                        if ("1.0".equals(is)){
//                                            return;
//                                        }
//                                    }
//                                    @Override
//                                    public void onError(String error) {
//                                        Utils.Toast(context,"验证患者是否失败！\n失败原因：" + error);
//                                    }
//                                });
//                            }
                            setInhabitantView();
                        }else {
                            clearInhabitantView();
                        }
                    }else {
                        clearInhabitantView();
                        inhabitantDTO = null;
                    }
                }
            }
        });

        if (inhabitantDTO != null){
            setInhabitantView();
        }

    }

    private void setInhabitantView(){
        binding.textView177.setText(inhabitantDTO.getNAME());
        if ("1".equals(inhabitantDTO.getSEX()))
            binding.textView179.setText("男");
        else if ("2".equals(inhabitantDTO.getSEX()))
            binding.textView179.setText("女");
        binding.textView183.setText(inhabitantDTO.getTEL());
        binding.textView184.setText(inhabitantDTO.getIDCARD());
    }

    private void clearInhabitantView(){
        binding.textView177.setText("");
        binding.textView179.setText("");
        binding.textView183.setText("");
        binding.textView184.setText("");
        Utils.Toast(context,"未查到该身份证的信息，请同步居民信息后再添加！");
    }


    /**
     * 判断是否有答案问题没有选择
     * @return
     */
    private boolean isAllChecked(){
        try {
            Class<? extends TCMHealthDTO> clazz = tcmHealthDTO.getClass();
            for (int i = 1; i <= 33; i++){
                String filedName = i > 9 ? "A" + i : "A0" + i;
                Field declaredField = clazz.getDeclaredField(filedName);
                declaredField.setAccessible(true);
                if (StringUtils.isNull(declaredField.get(tcmHealthDTO))){
                    Utils.Toast(context,"请将问题" + i + "选择后再进行下一步！");
                    return false;
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return false;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 保存
     */
    public void save(){

        //气虚质计算
        int qualityDeficiency = Integer.valueOf(tcmHealthDTO.getA02()) +
                Integer.valueOf(tcmHealthDTO.getA03()) +
                Integer.valueOf(tcmHealthDTO.getA04()) +
                Integer.valueOf(tcmHealthDTO.getA14());
        scores.put("Qi",qualityDeficiency);
        if (qualityDeficiency >= 11){
            tcmHealthDTO.setQualityDeficiency("1");
        }else if (qualityDeficiency <= 10 && qualityDeficiency >= 9){
            tcmHealthDTO.setQualityDeficiency("2");
        }else {
            tcmHealthDTO.setQualityDeficiency("0");
        }

        //阳虚质计算
        int yangQuality = Integer.valueOf(tcmHealthDTO.getA11()) +
                Integer.valueOf(tcmHealthDTO.getA12()) +
                Integer.valueOf(tcmHealthDTO.getA13()) +
                Integer.valueOf(tcmHealthDTO.getA29());
        scores.put("Yang",yangQuality);
        if (yangQuality >= 11){
            tcmHealthDTO.setYangQuality("1");
        }else if (yangQuality <= 10 && yangQuality >= 9){
            tcmHealthDTO.setYangQuality("2");
        }else {
            tcmHealthDTO.setYangQuality("0");
        }

        //阴虚质计算
        int yinQuality = Integer.valueOf(tcmHealthDTO.getA10()) +
                Integer.valueOf(tcmHealthDTO.getA21()) +
                Integer.valueOf(tcmHealthDTO.getA26()) +
                Integer.valueOf(tcmHealthDTO.getA31());
        scores.put("Yin",yinQuality);
        if (yinQuality >= 11){
            tcmHealthDTO.setYinQuality("1");
        }else if (yinQuality <= 10 && yinQuality >= 9){
            tcmHealthDTO.setYinQuality("2");
        }else {
            tcmHealthDTO.setYinQuality("0");
        }

        //痰湿质计算
        int phlegm = Integer.valueOf(tcmHealthDTO.getA09()) +
                Integer.valueOf(tcmHealthDTO.getA16()) +
                Integer.valueOf(tcmHealthDTO.getA28()) +
                Integer.valueOf(tcmHealthDTO.getA32());
        scores.put("Phlegm",phlegm);
        if (phlegm >= 11){
            tcmHealthDTO.setPhlegm("1");
        }else if (phlegm <= 10 && phlegm >= 9){
            tcmHealthDTO.setPhlegm("2");
        }else {
            tcmHealthDTO.setPhlegm("0");
        }

        //湿热质计算
        int dampHeat = Integer.valueOf(tcmHealthDTO.getA23()) +
                Integer.valueOf(tcmHealthDTO.getA25()) +
                Integer.valueOf(tcmHealthDTO.getA27()) +
                Integer.valueOf(tcmHealthDTO.getA30());
        scores.put("Hot",dampHeat);
        if (dampHeat >= 11){
            tcmHealthDTO.setDampHeat("1");
        }else if (dampHeat <= 10 && dampHeat >= 9){
            tcmHealthDTO.setDampHeat("2");
        }else {
            tcmHealthDTO.setDampHeat("0");
        }

        //血瘀质计算
        int bloodQuality = Integer.valueOf(tcmHealthDTO.getA19()) +
                Integer.valueOf(tcmHealthDTO.getA22()) +
                Integer.valueOf(tcmHealthDTO.getA24()) +
                Integer.valueOf(tcmHealthDTO.getA33());
        scores.put("Blood",bloodQuality);
        if (bloodQuality >= 11){
            tcmHealthDTO.setBloodQuality("1");
        }else if (bloodQuality <= 10 && bloodQuality >= 9){
            tcmHealthDTO.setBloodQuality("2");
        }else {
            tcmHealthDTO.setBloodQuality("0");
        }

        //气郁质计算
        int qiQuality = Integer.valueOf(tcmHealthDTO.getA05()) +
                Integer.valueOf(tcmHealthDTO.getA06()) +
                Integer.valueOf(tcmHealthDTO.getA07()) +
                Integer.valueOf(tcmHealthDTO.getA08());
        scores.put("StQi",qiQuality);
        if (qiQuality >= 11){
            tcmHealthDTO.setQiQuality("1");
        }else if (qiQuality <= 10 && qiQuality >= 9){
            tcmHealthDTO.setQiQuality("2");
        }else {
            tcmHealthDTO.setQiQuality("0");
        }

        //特秉质计算
        int teBingQuality = Integer.valueOf(tcmHealthDTO.getA15()) +
                Integer.valueOf(tcmHealthDTO.getA17()) +
                Integer.valueOf(tcmHealthDTO.getA18()) +
                Integer.valueOf(tcmHealthDTO.getA20());
        scores.put("Specific",teBingQuality);
        if (teBingQuality >= 11){
            tcmHealthDTO.setTeBingQuality("1");
        }else if (teBingQuality <= 10 && teBingQuality >= 9){
            tcmHealthDTO.setTeBingQuality("2");
        }else {
            tcmHealthDTO.setTeBingQuality("0");
        }

        //平和质计算
        int moderateQuality = Integer.valueOf(tcmHealthDTO.getA01()) +
                (5 - Integer.valueOf(tcmHealthDTO.getA02()) + 1) +
                (5 - Integer.valueOf(tcmHealthDTO.getA04()) + 1) +
                (5 - Integer.valueOf(tcmHealthDTO.getA05()) + 1) +
                (5 - Integer.valueOf(tcmHealthDTO.getA13()) + 1);
        scores.put("Peaceful",moderateQuality);
        if (moderateQuality >= 17 && qualityDeficiency <= 8 && yangQuality <= 8 &&
                yinQuality <= 8 && phlegm <= 8 && dampHeat <= 8 &&
                bloodQuality <= 8 && qiQuality <= 8 && teBingQuality <= 8){
            tcmHealthDTO.setModerateQuality("1");
        }else if (moderateQuality >= 17 && qualityDeficiency <= 10 && yangQuality <= 10 &&
                yinQuality <= 10 && phlegm <= 10 && dampHeat <= 10 &&
                bloodQuality <= 10 && qiQuality <= 10 && teBingQuality <= 10){
            tcmHealthDTO.setModerateQuality("2");
        }else {
            tcmHealthDTO.setModerateQuality("0");
        }


        //最高分体质
        tcmHealthDTO.setTcHealthHighScore(maxScore(scores));

        //病人信息
        tcmHealthDTO.setResident(inhabitantDTO.getID());
        tcmHealthDTO.setPersonName(inhabitantDTO.getNAME());

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 计算出最高分
     * @param map
     * @return
     */
    public String maxScore(Map<String, Integer> map){
        List<Integer> list = new ArrayList<>(new HashSet<Integer>(map.values()));
        Collections.sort(list);
        for (Map.Entry<String, Integer> entry : map.entrySet()){
            if (Objects.equals(entry.getValue(),list.get(list.size()-1))){
                return entry.getKey();
            }
        }
        return null;
    }

    /**
     * 隐藏Fragment
     */
    private void hideAddFragment() {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(0, R.anim.fragment_slide_down);
        ft.hide(this);
        ft.commitAllowingStateLoss();
    }

}
